/*
 * @Author: hongbin
 * @Date: 2022-03-27 17:10:45
 * @LastEditors: hongbin
 * @LastEditTime: 2022-04-04 22:04:31
 * @Description:自定义hook 设置 page 宽高
 */

import { useState } from "react";
import { useElementContext } from "../context/ElementContext";
import useMount from "./useMount";

interface ILayout {
  style: React.CSSProperties;
  /**
   * 缩放倍数 指和document的差值
   */
  scaleMultiple: number;
}

type IUsePageLayout = [
  layout: ILayout,
  /**
   * 是否全屏预览
   */
  fullScreen: boolean,
  /**
   * 切换全屏状态
   */
  toggleFullScreen: () => void
];

/**
 * @description: 自定义hook 设置 page 宽高 跟随设备宽高比
 * @param {React.RefObject<HTMLElement>} 外部容器 Ref
 * @param {React.RefObject<HTMLElement>} 具体要设置的元素 Ref
 * @return {[CSSProperties,preview,backLayout]}  宽高样式 全屏预览 恢复开发大小
 */
function usePageLayout(
  containerRef: React.RefObject<HTMLElement>,
  pageRef: React.RefObject<HTMLElement>
): IUsePageLayout {
  const { setPageAxis } = useElementContext();
  const [fullScreen, setFullScreen] = useState(false);
  const [layout, setLayout] = useState<ILayout>({
    style: { width: "0px", height: "0px" },
    scaleMultiple: 0,
  });

  useMount(() => {
    const setPageLayout = () => {
      const container = containerRef.current;
      const page = pageRef.current;
      if (container && page) {
        //跟随设备宽高比
        const { offsetHeight: BH, offsetWidth: BW } = document.body;
        const ratio = BH / BW;
        const shouldWidth = container.offsetWidth * 0.98;
        const width = shouldWidth + "px";
        const height = shouldWidth * ratio + "px";
        setLayout({
          style: { width, height },
          scaleMultiple: shouldWidth / BW,
        });
        //植入全局变量
        window.scaleMultiple = shouldWidth / BW;
        window.bodyWidth = BW;
        window.bodyHeight = BH;

        //下一帧再获取布局，确保布局生效后再获取 否则是按照宽高是0的位置获取的
        requestAnimationFrame(() => {
          // 确定坐标
          const minX = page.offsetLeft;
          const minY = page.offsetTop;
          const maxX = minX + page.offsetWidth;
          const maxY = minY + page.offsetHeight;
          setPageAxis({
            minX,
            minY,
            maxX,
            maxY,
            width: page.offsetWidth,
            height: page.offsetHeight,
          });
        });
      }
    };
    setPageLayout();
    window.addEventListener("resize", setPageLayout);

    return () => {
      window.removeEventListener("resize", setPageLayout);
    };
  });

  const toggleFullScreen = () => {
    setFullScreen((state) => !state);
  };

  return [layout, fullScreen, toggleFullScreen];
}

export default usePageLayout;
